import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  InspectionListCommand,
  getInspectionListApi,
  exportInspectionExcelApi,
  deleteInspectionApi
} from "@/api/airport/inspection/inspection";
import { http } from "@/utils/http";
// 获取静态字典信息（检查计划状态），添加状态映射

const statusMap = {
  ...useUserStoreHook().dictionaryMap["inspection.status"],
  '0': '计划待提交',
  '1': '计划待审批',
  '2': '计划已驳回',
  '3': '检查待开始',
  '4': '正在检查',
  '5': '已完成'
};


// 正式开始js代码，也就是页面初始化时会执行的代码
// 新增检查类型映射
const inspectionTypeMap = {
  '1': '法定自查',
  '2': '专项检查',
  '3': '安全质量检查'
};

export function useInspectionHook() {
  // 设置默认的排序规则descending和ascending两种
  const defaultSort: Sort = {
    prop: "createTime",
    order: "descending"
  };
  // 分页设置
  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  // 注意：这个函数是一个计算属性，也就是说当用户设置时间选择框的属性时，这个函数会自动执行，并且会将时间选择框的属性赋值给searchFormParams的beginTime和endTime
  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.startTime && searchFormParams.endTime) {
        return [searchFormParams.startTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.startTime = dayjs(v[0]).format('YYYY-MM-DD'); // 格式化日期
        searchFormParams.endTime = dayjs(v[1]).format('YYYY-MM-DD'); // 格式化日期
      } else {
        searchFormParams.startTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });
  // 创建一个响应式的对象，用于存储查询参数
  const searchFormParams = reactive<InspectionListCommand>({
    inspectionName: "",
    deptId: undefined,
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    createBy: "",
    inspectionType: undefined // 新增检查类型查询参数
  });

  // 表格数据
  const dataList = ref([]);
  // 标志：保存表格是否正在加载数据
  const pageLoading = ref(true);
  // 标志：保存表格是否有选中数据（用于存储用户在表格中选中的多条记录）
  const multipleSelection = ref([]);
  // 标志：保存表格的排序规则，在上面被初始化了
  const sortState = ref<Sort>(defaultSort);
  // 表格列配置
  // 定义状态对应的颜色映射
  const statusColorMap = {
    '0': 'info',
    '1': 'warning',
    '2': 'danger',
    '3': 'info',
    '4': 'primary',
    '5': 'success'
  };
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "检查编号",
      prop: "inspectionCode",
      minWidth: 150
    },
    {
      label: "检查类型",
      prop: "inspectionType",
      minWidth: 120,
      formatter: ({ inspectionType }) => {
        return inspectionTypeMap[inspectionType] || inspectionType;
      }
    },
    {
      label: "检查计划名称",
      prop: "inspectionName",
      minWidth: 180,
      slot: "inspectionName" // 添加 slot
    },
    {
      label: "检查对象",
      prop: "deptName",
      minWidth: 120
    },
    {
      label: "检查级别",
      prop: "inspectionLevel",
      minWidth: 80,
      formatter: ({ inspectionLevel }) => {
        switch (inspectionLevel) {
          case "1":
            return "公司级";
          case "2":
            return "部门级";
          case "3":
            return "科室级";
          default:
            return inspectionLevel;
        }
      }
    },
    {
      label: "计划日期",
      prop: "planDate",
      minWidth: 100,
      formatter: ({ planDate }) => dayjs(planDate).format("YYYY-MM-DD")
    },
    {
      label: "检查小组名单",
      prop: "userNameList",
      minWidth: 200,
      formatter: ({ userNameList }) => {
        // 判断 userNameList 是否为数组
        if (Array.isArray(userNameList)) {
          // 直接拼接数组元素
          return userNameList.join(', ');
        }
        return '';
      }
    },

    {
      label: "状态",
      prop: "status",
      minWidth: 120,
      cellRenderer: ({ row, props }) => {
        const status = row.status;
        const statusText = status !== undefined ? statusMap[String(status)] || '未知状态' : '未知状态';
        const statusColor = status !== undefined ? statusColorMap[String(status)] || 'info' : 'info';
        return (
          <el-tag
            size="large"
            type={statusColor}
            effect="plain"
          >
            {statusText}
          </el-tag>
        );
      }
    },
    {
      label: "检查项目数量",
      prop: "checkItemCount",
      minWidth: 120,
      formatter: ({ checkItemCount }) => checkItemCount !== undefined ? String(checkItemCount) : ''
    },
    {
      label: "检查进度",
      prop: "checkProgress",
      minWidth: 120,
      formatter: ({ checkProgress }) => checkProgress !== undefined ? `${Math.round(checkProgress)}%` : ''
    },
    {
      label: "创建人",
      prop: "createBy",
      minWidth: 120
    },
    {
      label: "开始时间",
      prop: "startTime",
      sortable: "custom",
      minWidth: 160,
      formatter: ({ startTime }) => startTime ? dayjs(startTime).format("YYYY-MM-DD HH:mm:ss") : '未开始'
    },
    {
      label: "结束时间",
      prop: "endTime",
      sortable: "custom",
      minWidth: 160,
      formatter: ({ endTime }) => endTime ? dayjs(endTime).format("YYYY-MM-DD HH:mm:ss") : '未结束'
    },
    {
      label: "操作",
      fixed: "right",
      width: 240, // 适当增加宽度以适应新按钮
      slot: "operation"
    }
  ];
  // 表格列的排序变化的时候，会触发这个函数
  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    // 表格列的排序变化的时候，需要重置分页
    pagination.currentPage = 1;
    // 表格列的排序变化的时候，需要重新查询数据
    getInspectionList();
  }
  // 表格的搜索按钮点击的时候，会触发这个函数
  async function onSearch() {
    // 重置排序
    sortState.value = defaultSort;
    // 重置分页
    pagination.currentPage = 1;
    // 重新查询数据
    await getInspectionList();
  }

  //  重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    // 清空查询参数
    formEl.resetFields();
    // 清空时间查询
    searchFormParams.startTime = undefined;
    searchFormParams.endTime = undefined;
    // 重置排序
    sortState.value = defaultSort;
    // 重置分页
    pagination.currentPage = 1;
    // 重新查询数据
    getInspectionList();
  }
  //  获取检查计划列表（查询数据）
  async function getInspectionList() {
    pageLoading.value = true;
    // 在查询之前，需要将查询参数赋值给searchFormParams，包括分页参数
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    // 将响应式对象通过toraw函数转化为普通对象
    const { data } = await getInspectionListApi(toRaw(searchFormParams)).finally(
      () => {
        pageLoading.value = false;
      }
    );
    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportInspectionExcelApi(toRaw(searchFormParams), "检查计划数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteInspectionApi([row.inspectionId]).then(() => {
      message(`您删除了编号为${row.inspectionId}的这条检查计划数据`, {
        type: "success"
      });
      // 刷新列表
      getInspectionList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的检查计划数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteInspectionApi(multipleSelection.value).then(() => {
          message(`您删除了编号为[ ${multipleSelection.value} ]的检查计划数据`, {
            type: "success"
          });
          // 刷新列表
          getInspectionList();
        });
      })
      .catch(() => {
        message("取消删除", {
          type: "info"
        });
        // 清空checkbox选择的数据
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(getInspectionList);

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getInspectionList,
    resetForm,
    handleDelete,
    handleBulkDelete
  };
}

// 根据部门 ID 查询用户列表
export const getUsersByDeptIdApi = (deptId: number) => {
  return http.request<{
    code: number;
    msg: string;
    data: Array<{
      creatorId: null | number;
      createTime: string;
      updaterId: null | number;
      updateTime: string;
      deleted: boolean;
      userId: number;
      postId: null | number;
      roleId: null | number;
      deptId: number;
      username: string;
      nickname: string;
      userType: number;
      email: string;
      phoneNumber: string;
      sex: number;
      avatar: string;
      password: string;
      status: number;
      loginIp: string;
      loginDate: null | string;
      isAdmin: boolean;
      remark: null | string;
    }>;
  }>(
    "get",
    `/system/users/dept/${deptId}`
  );
};

